/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ggsoft.timetracker.dao.impl;

import com.ggsoft.timetracker.dao.TimeTrackerDao;
import com.ggsoft.timetracker.domain.Timecard;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.appfuse.dao.hibernate.GenericDaoHibernate;
import org.appfuse.model.User;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

/**
 *
 * @author giovanella
 * @date May 17, 2014
 */
@Repository("timeTrackerDao")
public class TimeTrackerDaoImpl extends GenericDaoHibernate<Timecard, Long> implements TimeTrackerDao {
    
    public TimeTrackerDaoImpl() {
        super(Timecard.class);
    }

    @Override
    public Timecard findLastTimecard(User user) {
        String hql = "from Timecard this where this.loginTime is not null and this.logoutTime is null";

        List args = new ArrayList();

        if (user != null) {
            args.add(user.getId());
            hql += " and this.user.id = ?";
        }

        List results = find(hql, args.toArray(), 0);
        return results != null && !results.isEmpty() ? (Timecard) results.get(0) : null;
    }

    @Override
    public void storeTimeCard(Timecard timecard) {
        getSession().saveOrUpdate(timecard);
        getSession().flush();
    }        
    
    public List<Timecard> findTimecards(User user, String status, Date date) {
        String hql = "from Timecard this where 1 = 1";

        List args = new ArrayList();

        if (user != null) {
            args.add(user.getId());
            hql += " and this.user.id = ?";
        } else {
            hql += " and this.user.id = 0";
        }
        
        if (date != null) {
            args.add(date);
            hql += " and this.loginTime = ?";
        }

        List<Timecard> results = find(hql, args.toArray(), 0);
        
        return results;
    }

    public List find(String hql, Object[] args, int maxResults) {
        Query query = getSession().createQuery(hql);
        if (maxResults > 0) {
            query.setMaxResults(maxResults);
        }
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                query.setParameter(i, args[i]);
            }
        }
        return query.list();
    }    
}
